package cn.fl.customer.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.IPrjBillApplyService;
import cn.fl.customer.service.IPrjBillBscInfoService;
import cn.fl.customer.service.IPrjBillFeeRService;
import cn.fl.customer.utils.WebUtils;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.customer.vo.PrjBillApplyVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUsrService;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.invoice.condition.PrjBillBscInfoQueryCondition;
import fl.customer.facade.invoice.constant.PrjBillApplyConstant;
import fl.customer.facade.invoice.dto.InvoiceApplyReqDTO;
import fl.customer.facade.invoice.dto.PrjBillBscInfoDTO;
import fl.customer.facade.invoice.dto.ValidInvoiceDataDTO;
import fl.flow.facade.flow.api.IFlowQueryApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Description: 电子发票Controller
 * @Author: liurong
 * @CreateDate: 2020/6/2 14:21
 * @Version: 1.0
 */
@Controller
@RequestMapping("/invoice/electron")
public class InvoiceElectronController extends BaseController {

    /**
     * PrjBillFeeR 服务层BEAN
     */
    @Autowired
    private IPrjBillFeeRService prjBillFeeRService;

    /**
     * 服务层BEAN
     */
    @Autowired
    private IPrjBillApplyService prjBillApplyService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISysUsrService sysUsrService;
    @Autowired
    private IFlowQueryApiService flowQueryApiService;
    @Autowired
    private ICstBscInfoService cstBscInfoService;

    @Autowired
    private IPrjBillBscInfoService prjBillBscInfoService;

    /**
     * 到重新推送列表页面
     */
    @RequestMapping(value = "/toPushAgainPage.do", method = { RequestMethod.GET})
    public ModelAndView toPushAgainPage(HttpServletRequest request) {
        String applyId = request.getParameter("applyId");
        ModelAndView view = new ModelAndView("customer/invoice/toPushAgainPage");
        if (StringUtils.isNotEmpty(applyId)) {
            PrjBillApplyVO prjBillApplyVO = this.prjBillApplyService.selectById(Long.valueOf(applyId));
            view.addObject("email", prjBillApplyVO.getEmail());
        }
        view.addObject("applyId", applyId);
        return view;
    }

    /**
     * 重新推送
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/pushAgain.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object pushAgain(HttpServletRequest request) throws BaseException {
        String applyId = request.getParameter("applyId");
        String email = request.getParameter("email");
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            if (StringUtils.isEmpty(applyId)) {
                throw new BaseException("开票申请id不能为空");
            }
            if (StringUtils.isEmpty(email)) {
                throw new BaseException("email不能为空");
            }
            PrjBillApplyVO prjBillApplyVO = new PrjBillApplyVO();
            prjBillApplyVO.setId(Long.valueOf(applyId));
            prjBillApplyVO.setEmail(email);
            this.prjBillApplyService.executePush(prjBillApplyVO);
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("重新推送发票失败").setKeys("applyId:" + applyId).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(ex.getMessage());
        } catch (Exception ex) {
            BaseLogUtils.newLogger("重新推送发票失败").setKeys("applyId:" + applyId).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(ex.getMessage());
        }
        return resultVO;
    }

    /**
     * 到电子发票详情页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        String applyId = request.getParameter("id");
        String isGetUrl = request.getParameter("isGetUrl");
        ModelAndView view = new ModelAndView("customer/invoice/cstInvoiceElectronDetail");
        view.addObject("applyId", applyId);
        PrjBillBscInfoQueryCondition prjBillBscInfoQueryCondition = new PrjBillBscInfoQueryCondition();
        prjBillBscInfoQueryCondition.setApplyId(Long.valueOf(applyId));
        List<PrjBillBscInfoDTO> prjBillBscInfoDTOS = this.prjBillBscInfoService.searchBillBscInfoList(prjBillBscInfoQueryCondition);
        if (CollectionUtils.isNotEmpty(prjBillBscInfoDTOS)) {
            view.addObject("bscInfoId", prjBillBscInfoDTOS.get(0).getId());
        }
        view.addObject("isGetUrl", isGetUrl);
        return view;
    }

    /**
     * 到申请电子发票页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toApplyPage.do", method = { RequestMethod.GET})
    public ModelAndView toApplyPage(HttpServletRequest request, HttpServletResponse response) {
        String cstId = request.getParameter("cstId");
        String cstNm = request.getParameter("cstNm");
        String flag = request.getParameter("flag");
        ModelAndView view = new ModelAndView("customer/invoice/cstInvoiceElectronApply");

        // 查询客户信息
        CstBscInfoVO cstBscInfoVO = this.cstBscInfoService.selectById(Long.valueOf(cstId));
        Map<String, String> cstTypCdMap = sysDictionaryApiService.searchGroupToMap(PrjBillApplyConstant.SYS_CD, PrjBillApplyConstant.ORG_CD, DictionaryConstant.CODE_GRP_CST_TYP_CD);

        List<KeyValueVO> cntNosKV = this.prjBillApplyService.queryPrjByCstId(Long.valueOf(cstId));
        List<KeyValueVO> feeTyps = this.prjBillApplyService.querySupportFeeTyp(PrjBillApplyConstant.BILL_WAY_CD_1);
        view.addObject("feeTyps", JSON.toJSON(feeTyps));
        view.addObject("cstTypCd", cstBscInfoVO.getCstTypCd());
        view.addObject("cstTypNm", cstTypCdMap.get(cstBscInfoVO.getCstTypCd()));
        view.addObject("cntNosKV", JSON.toJSON(cntNosKV));
        view.addObject("cstId", cstId);
        view.addObject("cstNm", cstNm);
        view.addObject("flag", flag);
        view.addObject("flag", flag);
        // 申请人姓名
        view.addObject("applyNm", CurrentThreadContext.getCurrentUserName());
        view.addObject("orgCd", CurrentThreadContext.getCurrentOrgCd());//当前组织架构
        view.addObject("orgCdNm", CurrentThreadContext.getCurrentOrgDispNm());//当前组织架构
        return view;
    }

    /**
     * 申请电子发票并保存数据
     */
    @RequestMapping(value = "/apply.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object apply(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        InvoiceApplyReqDTO reqDTO = null;
        DataResultDTO resultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String paySchFeeList = request.getParameter("paySchFeeList");
            if (StringUtils.isEmpty(paySchFeeList)) {
                throw new BaseException("请选择需要开票的费用项数据！");
            }
            List<ValidInvoiceDataDTO> validInvoiceDataDTOS = JSON.parseArray(paySchFeeList, ValidInvoiceDataDTO.class);
            if (CollectionUtils.isEmpty(validInvoiceDataDTOS)) {
                throw new BaseException("请选择需要开票的费用项数据！");
            }
            reqDTO = WebUtils.getRequestBean(request, InvoiceApplyReqDTO.class);
            reqDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            reqDTO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            reqDTO.setNeedInvoiceList(validInvoiceDataDTOS);
            resultDTO = this.prjBillApplyService.executeDoInvoiceElectron(reqDTO);
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("电子发票申请异常").setKeys("reqDTO:" + JSON.toJSONString(reqDTO)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo(ex.getMessage());
        } catch (Exception ex) {
            BaseLogUtils.newLogger("电子发票申请异常").setKeys("reqDTO:" + JSON.toJSONString(reqDTO)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo(ex.getMessage());
        }
        return resultDTO;
    }

    /**
     * 冲红电子发票
     */
    @RequestMapping(value = "/revertInvoice.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object revertInvoice(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {

        } catch (BaseException ex) {
            // BaseLogUtils.newLogger("电子发票申请异常").setKeys("entity:" + JSON.toJSONString(entity)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            // BaseLogUtils.newLogger("电子发票申请异常").setKeys("entity:" + JSON.toJSONString(entity)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }

    /**
     * 获取文件下载地址
     */
    @RequestMapping(value = "/getDownloadUrl.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object getDownloadUrl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        // 发票信息id
        String bscInfoId = request.getParameter("bscInfoId");
        try {
            if (StringUtils.isEmpty(bscInfoId)) {
                throw new BaseException("票据id不能为空");
            }
            String downloadUrl = this.prjBillApplyService.getDownloadUrl(Long.valueOf(bscInfoId));
            if (StringUtils.isNotEmpty(downloadUrl)) {
                result.setData(downloadUrl);
            }
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("获取文件下载地址异常").setKeys("bscInfoId:" + JSON.toJSONString(bscInfoId)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("获取文件下载地址异常").setKeys("bscInfoId:" + JSON.toJSONString(bscInfoId)).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }


}

